<template>
  <div class="attractions-info">
    <headers></headers>
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 图片轮播和基本信息 -->
      <div class="info-container">
        <div class="carousel-section">
          <el-carousel height="500px" indicator-position="outside">
            <el-carousel-item v-for="(item,index) in info.images.split(',')" :key="index">
              <img :src="item" alt="景点图片">
            </el-carousel-item>
          </el-carousel>
        </div>
        
        <div class="info-section">
          <h1 class="attraction-name">{{info.name}}</h1>
          <div class="price-section">
            <span class="price-label">价格：</span>
            <span class="price-amount">¥{{info.price}}</span>
          </div>
          <div class="stock-info">
            <el-tag :type="info.num > 20 ? 'success' : 'warning'" effect="plain">
              库存: {{info.num}}
            </el-tag>
            <el-tag type="info" effect="plain" class="auth-tag">
              {{info.realName == 0 ? '非实名预约' : '需要实名认证'}}
            </el-tag>
          </div>
          <div class="description">{{info.introduce}}</div>
          <div class="action-buttons">
            <el-button type="primary" icon="el-icon-date" @click="toOrder">立即预约</el-button>
            <el-button type="success" icon="el-icon-chat-line-square" @click="toComment">查看评论</el-button>
          </div>
        </div>
      </div>

      <!-- 详细信息卡片 -->
      <div class="details-card">
        <el-card>
          <div class="detail-section">
            <h3><i class="el-icon-info"></i> 详细介绍</h3>
            <p>{{info.content}}</p>
          </div>
          <div class="detail-section">
            <h3><i class="el-icon-warning"></i> 预约须知</h3>
            <p>{{info.open}}</p>
          </div>
          <div class="detail-section">
            <h3><i class="el-icon-time"></i> 入园时间</h3>
            <p>{{info.time}}</p>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 预约弹窗 -->
    <el-dialog
      title="预约信息"
      :visible.sync="dialogVisible"
      width="600px"
      custom-class="booking-dialog">
      <div class="booking-form">
        <div class="form-section">
          <el-form :model="bookingForm" label-width="100px">
            <el-form-item label="预约人数">
              <el-input-number 
                v-model="num" 
                :min="1" 
                :max="10"
                size="small"
                @change="handleNumChange"
                class="custom-number-input">
              </el-input-number>
            </el-form-item>
            
            <el-form-item label="预约日期">
              <el-date-picker
                v-model="date1"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择预约日期"
                :picker-options="{
                  disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                  }
                }"
                size="small"
                class="custom-date-picker">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>

        <div class="visitors-info">
          <div v-for="(item, index) in people" :key="index" class="visitor-form">
            <div class="visitor-header">
              <h4>访客 {{index + 1}}</h4>
              <div class="visitor-actions">
                <el-button 
                  v-if="index === (people.length - 1) && people.length < num" 
                  type="text" 
                  icon="el-icon-plus"
                  class="action-button add"
                  @click="addKeyword">
                  添加访客
                </el-button>
                <el-button 
                  v-if="index !== 0" 
                  type="text" 
                  icon="el-icon-delete"
                  class="action-button remove"
                  @click="minusKeyword(index)">
                  移除
                </el-button>
              </div>
            </div>
            
            <el-form 
              :model="item" 
              :rules="rules"
              :ref="`visitorForm${index}`"
              label-width="100px" 
              class="visitor-fields">
              <el-form-item label="姓名" prop="name">
                <el-input 
                  v-model="item.name" 
                  placeholder="请输入姓名" 
                  class="custom-input">
                </el-input>
              </el-form-item>
              <el-form-item label="联系电话" prop="tel">
                <el-input 
                  v-model="item.tel" 
                  placeholder="请输入11位手机号" 
                  maxlength="11"
                  show-word-limit
                  class="custom-input">
                </el-input>
              </el-form-item>
              <el-form-item 
                v-if="info.realName == 1" 
                label="身份证号" 
                prop="idCard">
                <el-input 
                  v-model="item.idCard" 
                  placeholder="请输入18位身份证号" 
                  maxlength="18"
                  show-word-limit
                  class="custom-input">
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeOrder" plain>取 消</el-button>
        <el-button type="primary" @click="saveOrder">确认预约</el-button>
      </div>
    </el-dialog>

    <bottoms></bottoms>
  </div>
</template>

<script>
  import {getSysAttractionsById,saveSysAttractionOrder} from '../../api/api'
  import headers from '@/components/header'
  import bottoms from '@/components/bottom'
  export default {
    data() {
      // 手机号验证规则
      const validatePhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入手机号'));
        } else if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的11位手机号'));
        } else {
          callback();
        }
      };
      
      // 身份证号验证规则
      const validateIdCard = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入身份证号'));
        } else if (!/^\d{17}[\dXx]$/.test(value)) {
          callback(new Error('请输入正确的18位身份证号'));
        } else {
          callback();
        }
      };

      return{
        id: "",
        dialogVisible: false,
        info: {},
        num: "",
        rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
          tel: [
            { required: true, validator: validatePhone, trigger: 'blur' }
          ],
          idCard: [
            { required: true, validator: validateIdCard, trigger: 'blur' }
          ]
        },
        people: [
            {
                name: "",
                tel: "",
                idCard: ""
            }
        ],
        date1: ""
      }
    },
    components: {
      headers,
      bottoms
    },
    methods: {
      closeOrder() {
        this.date1 = ""
        this.num = ""
        this.people = [
            {
                name: "",
                tel: "",
                idCard: ""
            }
        ],
        this.dialogVisible = false
      },
      saveOrder() {
          // 验证所有访客表单
          const validateForms = () => {
            const promises = this.people.map((_, index) => {
              return new Promise((resolve) => {
                const formRef = this.$refs[`visitorForm${index}`];
                if (!formRef) {
                  console.error(`Form reference visitorForm${index} not found`);
                  resolve(false);
                  return;
                }
                // 因为动态ref会返回数组，所以需要取第一个元素
                const form = Array.isArray(formRef) ? formRef[0] : formRef;
                if (!form || typeof form.validate !== 'function') {
                  console.error(`Invalid form reference for visitorForm${index}`);
                  resolve(false);
                  return;
                }
                form.validate((valid) => {
                  resolve(valid);
                });
              });
            });
            return Promise.all(promises).then(results => {
              return results.every(valid => valid);
            });
          };

          validateForms().then(valid => {
            if (valid) {
              if (!this.date1) {
                this.$message({
                    message: '请选择预约时间',
                    type: 'warning'
                });
                return;
              }
              
              if (this.people.length < this.num) {
                this.$message({
                    message: '请完善预约人信息',
                    type: 'warning'
                });
                return;
              }
              
              if (this.people.length > this.num) {
                this.$message({
                    message: '预约人信息超出预约人数',
                    type: 'warning'
                });
                return;
              }

              var param = {
                attractionsId: this.id,
                num: this.num,
                time: this.date1,
                people: JSON.stringify(this.people)
              }
              
              saveSysAttractionOrder(param).then(res => {
                  if (res.code == 1000) {
                    this.$message({
                        message: '预约成功，请等待确认',
                        type: 'success'
                    });
                    this.closeOrder()
                  } else {
                    this.$message({
                        message: res.message,
                        type: 'warning'
                    });
                  }
              })
            }
          });
      },
      getSysAttractionsById() {
          getSysAttractionsById({id: this.id}).then(res => {
              if (res.code == 1000) {
                  this.info = res.data
              }
          })
      },
      toOrder() {
          this.dialogVisible = true
      },
      toComment() {
          this.$router.push(`/attractionsComment?id=${this.id}&name=${this.info.name}`)
      },
      addKeyword() {
        var param = {
            name: "",
            tel: "",
            idCard: ""
        }
        this.people.push(param)
      },
      minusKeyword(index) {
        this.people.splice(index,1)
      },
      handleNumChange(value) {
        const currentLength = this.people.length;
        if (value > currentLength) {
          for (let i = currentLength; i < value; i++) {
            this.addKeyword();
          }
        } else if (value < currentLength) {
          this.people.splice(value, currentLength - value);
        }
      }
    },
    mounted() {
      this.id = this.$route.query.id
      this.getSysAttractionsById()
    }
 }
</script>

<style scoped>
.attractions-info {
  background-color: #f5f7fa;
  min-height: 100vh;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 轮播图和基本信息布局 */
.info-container {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 30px;
  margin-bottom: 30px;
}

.carousel-section {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.carousel-section img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 基本信息样式 */
.info-section {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.attraction-name {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.price-section {
  margin: 20px 0;
}

.price-label {
  font-size: 16px;
  color: #606266;
}

.price-amount {
  font-size: 28px;
  color: #f56c6c;
  font-weight: 600;
}

.stock-info {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

.auth-tag {
  margin-left: 10px;
}

.description {
  margin: 20px 0;
  color: #606266;
  line-height: 1.6;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

/* 详细信息卡片样式 */
.details-card {
  margin-bottom: 40px;
}

.detail-section {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.detail-section:last-child {
  border-bottom: none;
}

.detail-section h3 {
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-section p {
  color: #606266;
  line-height: 1.6;
}

/* 预约弹窗样式 */
:deep(.booking-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.booking-dialog .el-dialog__header) {
  background: #f8f9fa;
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid #eee;
}

:deep(.booking-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.booking-dialog .el-dialog__body) {
  padding: 30px;
}

:deep(.booking-dialog .el-dialog__footer) {
  border-top: 1px solid #eee;
  padding: 15px 30px;
}

.booking-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.booking-form::-webkit-scrollbar {
  width: 6px;
}

.booking-form::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.visitor-form {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.visitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.visitor-header h4 {
  font-size: 16px;
  color: #2c3e50;
  margin: 0;
  font-weight: 600;
}

.visitor-actions {
  display: flex;
  gap: 10px;
}

.action-button {
  padding: 0;
}

.action-button.add {
  color: #409EFF;
}

.action-button.remove {
  color: #F56C6C;
}

.visitor-fields {
  display: grid;
  gap: 15px;
}

:deep(.custom-input .el-input__inner) {
  border-radius: 4px;
  height: 36px;
}

:deep(.custom-number-input .el-input__inner) {
  width: 120px;
}

:deep(.custom-date-picker) {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .info-container {
    grid-template-columns: 1fr;
  }
  
  .info-section {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .visitor-form {
    padding: 15px;
  }

  :deep(.booking-dialog) {
    width: 90% !important;
    margin: 0 auto;
  }

  :deep(.booking-dialog .el-dialog__body) {
    padding: 20px;
  }
}
</style>
